#!/usr/bin/env python
# encoding: utf-8

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from ui.baseSet import Ui_Dialog
import os
import binascii
import configparser

from common.libs.ComDeal import WATER_CMD
from common.libs.MathFunc import MathFunc 

class BaseSetDialog(QDialog, Ui_Dialog):
    signal_serial_send = pyqtSignal(list)
    signal_update = pyqtSignal()
    def __init__(self, parent=None, serial=None):
        super(QDialog, self).__init__(parent)
        self.setupUi(self)
        # 串口模块
        self.serial = serial
        self.configfile = os.getcwd()+'/conf/base.ini'
        self.pushButton_default.clicked.connect(self.default)
        self.pushButton_read.clicked.connect(self.cmdReadFlash)
        self.pushButton_write.clicked.connect(self.cmdWriteFlash)

        # self.pushButton_.clicked.connect(self.writeConfig)
        self.lineEdit_measureSpeed.setValidator(QRegExpValidator(QRegExp("[0-9]+$"), self.lineEdit_measureSpeed))
        self.lineEdit_moveSpeed.setValidator(QRegExpValidator(QRegExp("[0-9]+$"), self.lineEdit_moveSpeed))
        self.lineEdit_pulse.setValidator(QRegExpValidator(QRegExp("[0-9]+$"), self.lineEdit_pulse))

        self.pushButton_saveConfig.clicked.connect(self.writeConfig)
        self.pushButton_readConfig.clicked.connect(self.readConfig)

        self.period = 0
        self.pulse = 0
        self.measure_speed = 0
        self.move_speed = 0
        # 相关变量
        self.scale_k = 0
        self.scale_b = 0
        self.scale_k_2 = 0
        self.scale_b_2 = 0
        self.task_auto = False
        self.task_stop_err = 100
        self.direction_x = 0
        self.direction_y = 0
        self.direction_z = 0
        # 显示曲线是否需要修正
        self.task_show = 'modify'

        self.axis_x = 0
        self.axis_y = 0
        self.axis_z = 0
        self.angle = 0

        # 读取配置文件中参数
        self.readConfig()

    def default(self):
        """默认配置"""
        self.lineEdit_measureSpeed.setText('20')
        self.lineEdit_moveSpeed.setText('40')
        self.comboBox_period.setCurrentIndex(2)

    def serial_deal(self, cmd, data):
        """ 串口接收 """
        if cmd == '42':
            QMessageBox.information(self,'提示','写入参数成功',QMessageBox.Yes)
        if cmd == '43':
            self.updateRead(data[2:])
            QMessageBox.information(self,'提示','读取参数成功',QMessageBox.Yes)
        if cmd == '82':
            # 读取信息
            _len = int(data[0:2], 16)
            # flash信息处理
            flash_start = 2
            flash_end = 2+_len*2
            flash_info = data[flash_start:flash_end]
            self.updateRead(flash_info)
            # 坐标信息处理
            axis_start = flash_end
            axis_end = flash_end + 3*4*2
            axis_info = data[axis_start:axis_end]

            self.axis_x = MathFunc.hexStrToNeg(axis_info[0:8])/self.pulse
            self.axis_y = MathFunc.hexStrToNeg(axis_info[8:16])/self.pulse
            self.axis_z = MathFunc.hexStrToNeg(axis_info[16:24])/self.pulse
            # self.signalOpengl.emit(self.real_x, self.real_y, self.real_z)
            # 摆放位置
            angle_start = axis_end
            angle_end = axis_end + 2
            angle_info = data[angle_start:angle_end]
            self.angle = angle_info 
            # self.proj_dock.treeWidget.pddDlg.styleSet(angle_info)
            # self.proj_dock.treeWidget.oarDlg.styleSet(angle_info)
            # self.actionEnabled(['start','env','repeat'])
            self.signal_update.emit()
            QMessageBox.information(self, '提示', '下位机信息读取成功！', QMessageBox.Yes)

    def updateRead(self, cmd_data):
        """串口读取flash数据处理"""
        cmd = cmd_data
        data = []
        self.period = int(cmd[0:4], 16)
        self.pulse = int(cmd[4:8], 16)
        f = (72000000/self.pulse/2)
        self.measure_speed = int(f/int(cmd[8:12], 16))
        self.move_speed = int(f/int(cmd[12:16], 16))

        self.scale_k = int(cmd[16:24], 16)/100000
        self.scale_b = int(cmd[24:32], 16)/100000
        self.scale_k_2 = int(cmd[32:40], 16)/100000
        self.scale_b_2 = int(cmd[40:48], 16)/100000

        # self.direction_x = int(cmd[48:52], 16)
        # self.direction_y = int(cmd[52:56], 16)
        # self.direction_z = int(cmd[56:60], 16)
        self.setParameter()
        # 更新参数
        self.signal_update.emit()

    def getWrite(self):
        """获取配置参数"""
        # 测量周期
        period        = int(float(self.comboBox_period.currentText().replace('ms','')))
        # 电机脉冲
        pulse         = int(float(self.lineEdit_pulse.text()))
        measure_speed = int(float(self.lineEdit_measureSpeed.text()))
        move_speed    = int(float(self.lineEdit_moveSpeed.text()))
        f = (72000000/int(pulse)/2)
        measure_speed = f/int(measure_speed)
        move_speed  = f/int(move_speed)

        # 刻度系数
        scale_k = int(float(self.lineEdit_scale_k.text())*100000)
        scale_b = int(float(self.lineEdit_scale_b.text())*100000)
        scale_k_2 = int(float(self.lineEdit_scale_k_2.text())*100000)
        scale_b_2 = int(float(self.lineEdit_scale_b_2.text())*100000)

        # 电机方向
        # direction_x = self.comboBox_direction_x.currentIndex()
        # direction_y = self.comboBox_direction_y.currentIndex()
        # direction_z = self.comboBox_direction_z.currentIndex()
        if measure_speed > 60000 or move_speed > 60000:
            QMessageBox.warning(self,'提示','参数设置错误',QMessageBox.Yes)
            return False
        else:
            cmd = '%s%s%s%s%s%s%s%s'%(
                hex(int(period)).replace('0x','').zfill(4).upper(),
                hex(int(pulse)).replace('0x','').zfill(4).upper(),
                hex(int(measure_speed)).replace('0x','').zfill(4).upper(),
                hex(int(move_speed)).replace('0x','').zfill(4).upper(),
                hex(int(scale_k)).replace('0x','').zfill(8).upper(),
                hex(int(scale_b)).replace('0x','').zfill(8).upper(),
                hex(int(scale_k_2)).replace('0x','').zfill(8).upper(),
                hex(int(scale_b_2)).replace('0x','').zfill(8).upper(),
                # hex(int(direction_x)).replace('0x','').zfill(4).upper(),
                # hex(int(direction_y)).replace('0x','').zfill(4).upper(),
                # hex(int(direction_z)).replace('0x','').zfill(4).upper(),
            )
            _len = hex(int(len(cmd)/2)).replace('0x','').zfill(2).upper()
            return _len+cmd
    def cmdReadInfo(self):
        cmd = WATER_CMD['读取信息']
        cmd[4] = '18'
        self.signal_serial_send.emit(cmd)

    def cmdReadFlash(self):
        """读取flash内容"""
        cmd = WATER_CMD['数据读取']
        _len = 4+4+4+4+8+8+8+8
        cmd[4] = hex(int(_len/2)).replace('0x','').zfill(2).upper()
        self.signal_serial_send.emit(cmd)

    def cmdWriteFlash(self):
        """写入flash内容"""
        cmd = WATER_CMD['数据写入']
        res = self.getWrite()
        if res:
            cmd[4] = res
            self.signal_serial_send.emit(cmd)

    def writeConfig(self):
        """写入配置文件中"""
        try:
            config = configparser.RawConfigParser()
            # 添加condition选项
            self.getParameter()


            config.add_section("base")
            config.set("base", "period", str(self.period))
            config.set("base", "pulse", str(self.pulse))
            config.set("base", "measure_speed", str(self.measure_speed))
            config.set("base", "move_speed", str(self.move_speed))
            if self.task_auto:
                config.set("base", "task_auto", 'True')
            else:
                config.set("base", "task_auto", 'False')
            config.set("base", "task_show", self.task_show)
            config.set("base", "task_stop_err", str(self.task_stop_err))
            # 写入并保存文件到当前项目文件夹下
            with open(self.configfile, 'w') as configfile:
                config.write(configfile)
            QMessageBox.information(self,"提示","保存成功", QMessageBox.Yes)
        except Exception as e:
            QMessageBox.warning(self,"错误","%s"%e, QMessageBox.Yes)

    def readConfig(self):
        try:
            config = configparser.ConfigParser()
            config.read(self.configfile)
            self.period        = int(config['base']['period'])
            self.pulse         = int(config['base']['pulse'])
            self.measure_speed = int(config['base']['measure_speed'])
            self.move_speed    = int(config['base']['move_speed'])
            task_auto = config['base']['task_auto']
            if task_auto == 'True':
                self.task_auto = True
            else:
                self.task_auto = False
            self.task_show = config['base']['task_show']
            self.task_stop_err= int(config['base']['task_stop_err'])
            self.setParameter()
        except Exception as e:
            QMessageBox.warning(self,"错误","%s"%e, QMessageBox.Yes)

    def getParameter(self):
        """获取参数"""
        self.period        = int(self.comboBox_period.currentText().replace('ms',''))
        self.pulse         = int(self.lineEdit_pulse.text())
        self.measure_speed = int(self.lineEdit_measureSpeed.text())
        self.move_speed    = int(self.lineEdit_moveSpeed.text())
        if self.comboBox_taskAuto.currentText() == '自动':
            self.task_auto = True
        else:
            self.task_auto = False
        if self.comboBox_taskShow.currentText() == '原始':
            self.task_show = 'original'
        else:
            self.task_show = 'modify'
        self.task_stop_err = int(self.lineEdit_taskStopErr.text())

    def setParameter(self):
        for i in range(0,self.comboBox_period.count()):
            if self.comboBox_period.itemText(i) == '%sms'%self.period:
                self.comboBox_period.setCurrentIndex(i)
                break
        self.lineEdit_pulse.setText(str(self.pulse))
        self.lineEdit_measureSpeed.setText(str(self.measure_speed))
        self.lineEdit_moveSpeed.setText(str(self.move_speed))
        self.lineEdit_scale_k.setText(str('%.5f'%self.scale_k))
        self.lineEdit_scale_b.setText(str('%.5f'%self.scale_b))
        self.lineEdit_scale_k_2.setText(str('%.5f'%self.scale_k_2))
        self.lineEdit_scale_b_2.setText(str('%.5f'%self.scale_b_2))
        if self.task_auto:
            self.comboBox_taskAuto.setCurrentIndex(1)
        else:
            self.comboBox_taskAuto.setCurrentIndex(0)
        if self.task_show == "original":
            self.comboBox_taskShow.setCurrentIndex(0)
        else:
            self.comboBox_taskShow.setCurrentIndex(1)
        # self.comboBox_direction_x.setCurrentIndex(self.direction_x)
        # self.comboBox_direction_y.setCurrentIndex(self.direction_y)
        # self.comboBox_direction_z.setCurrentIndex(self.direction_z)

        self.lineEdit_taskStopErr.setText(str(self.task_stop_err))



if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    window = BaseSetWidget()
    window.show()
    app.exec_()
